/**
 * 
 */
package com.gcgt.server.trader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.StringTokenizer;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

/**
 * @author Vincentas
 *
 */
public class YahooFinanceCvsIterator implements Iterator<MarketUpdate> {

	private final LineIterator values;

	public YahooFinanceCvsIterator(String url) throws MalformedURLException, IOException {
		this(new InputStreamReader(new URL(url).openStream()));
//		HttpClient a = new HttpClient();
//		GetMethod method = new GetMethod(url);
//		a.executeMethod(method);
//		this(new InputStreamReader(method.getResponseBodyAsStream());
	}
	
	public YahooFinanceCvsIterator(Reader reader) {
		values = IOUtils.lineIterator(reader);
		
		// skip first header line
		if (values.hasNext()) {
			values.next();
		}
	}
	
	@Override
	public boolean hasNext() {
		return values.hasNext();
	}

	@Override
	public MarketUpdate next() {
		String line = values.nextLine();
		StringTokenizer tokenizer = new StringTokenizer(line, ",");
		
		try {
			MarketUpdate marketUpdate = new MarketUpdate();
			marketUpdate.setDate(new SimpleDateFormat("yyyy-MM-dd").parse(tokenizer.nextToken()));
			marketUpdate.setOpen(new BigDecimal(tokenizer.nextToken()));
			marketUpdate.setHigh(new BigDecimal(tokenizer.nextToken()));
			marketUpdate.setLow(new BigDecimal(tokenizer.nextToken()));
			marketUpdate.setClose(new BigDecimal(tokenizer.nextToken()));
			marketUpdate.setVolume(Long.parseLong(tokenizer.nextToken()));
			marketUpdate.setTicker("OPT");
	
			return marketUpdate;
		} catch (Throwable throwable) {
			throwable.printStackTrace();
			return null;
		}
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();		
	}

}
